// A rubber band control class, based upon the rubber banding described in
// Graphic Java - Mastering the AWT (2nd Edition)
// David M. Geary
// The SunSoft Press - Java Series
//
package com.chrishobson.awt;

import java.awt.*;
import java.awt.event.*;

public class RubberBand {
  public RubberBand(Component c) {
    m_c = c;

    m_c.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
	anchor(e.getPoint());
      }
      public void mouseClicked(MouseEvent e) {
	end(e.getPoint());
      }
      public void mouseReleased(MouseEvent e) {
	end(e.getPoint());
      }
    });

    m_c.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {
	stretch(e.getPoint());
      }
    });

  }

  public void anchor(Point p) {
    if(m_state == 0) {
      m_state = 1;
      m_anchor.setLocation(p);
      started();
    }
  }

  public void stretch(Point p) {
    if(m_state > 0) {
      Graphics g = m_c.getGraphics();
      if(g != null) {
	g.setXORMode(m_c.getBackground());
	g.setColor(Color.green);
	if(m_state == 1) {
	  m_state = 2;
	} else {
	  draw(g);
	}
	m_last.setLocation(p);
	draw(g);
	g.dispose();
      }
    }
  }

  public void end(Point p) {
    if(m_state > 0) {
      Graphics g = m_c.getGraphics();
      if(g != null) {
	g.setXORMode(m_c.getBackground());
	g.setColor(Color.green);
	draw(g);
	g.dispose();
      }
      ended();
      m_state = 0;
    }
  }


  protected void draw(Graphics g) {}
  protected void started() {}
  protected void ended() {}
  

  protected Point m_anchor = new Point();
  protected Point m_last = new Point();
  private int m_state = 0;
  private Component m_c;
}
